package com.xuxin.baby.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import org.jetbrains.annotations.NotNull;

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by xu_xin
 * Created on 2020.08.13 0013
 * 计时器从0开始计时
 */
public class TimeView extends AppCompatTextView {
    private Timer timer;
    private TimerTask task;
    private int second;//秒,时间单位

    public TimeView(Context context) {
        super(context);
    }

    public TimeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void startTimer(long time) {
        if (null != timer && null != task) {
            return;
        }
        second = (int) ((System.currentTimeMillis() - time) / 1000);
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0);
            }
        };
        timer.schedule(task, 0, 1000);
    }

    public void stopTimer() {
        if (task != null) {
            task.cancel();
            task = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NotNull Message message) {
            setText(getTime(second));
            second++;
            return false;
        }
    });

    public String getTime(int second) {
        StringBuilder sb = new StringBuilder();
        int days = second / (60 * 60 * 24);
        int hours = (second % (60 * 60 * 24)) / (60 * 60);
        int minutes = (second % (60 * 60)) / 60;
        int seconds = second % 60;
        DecimalFormat format = new DecimalFormat("00");
        if (days > 0 || hours > 0) {
            sb.append(format.format(hours)).append(" : ").append(format.format(minutes)).append(" : ").append(format.format(seconds));
        } else {
            sb.append(format.format(minutes)).append(" : ").append(format.format(seconds));
        }
        return sb.toString();
    }
}